package com.beiye.drivertransport.accident.training;


import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.DaikaoAndHavetestCourseBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEventTest;
import com.example.mylibrary.paper.utils.DensityUtils;
import com.example.mylibrary.paper.utils.QuestionAnswerUtils;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;


/**事故培训题目
 */
public class QuestionAccidenttrainingExaminationFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private boolean isViewCreate;//view是否已创建
    private boolean isViewVisible;//fragment是否可见
    ArrayList<String> opitionList=new ArrayList<>();
    ArrayList<Integer> checkboxList=new ArrayList<>();
    private int position;
    private View view;
    private DaikaoAndHavetestCourseBean.RowsBean rowsBean;
   // private Animation animation;


    public QuestionAccidenttrainingExaminationFragment() {
    }

    public static QuestionAccidenttrainingExaminationFragment newInstance(DaikaoAndHavetestCourseBean.RowsBean rowsBean, int position) {
        QuestionAccidenttrainingExaminationFragment fragment = new QuestionAccidenttrainingExaminationFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, rowsBean);
        args.putSerializable(ARG_PARAM2, position);
        fragment.setArguments(args);
        return fragment;
    }

//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        if (getArguments() != null) {
//            rowsBean = (DaikaoAndHavetestCourseBean.RowsBean) getArguments().getSerializable(ARG_PARAM1);
//            position = getArguments().getInt(ARG_PARAM2);
//
//        }
//    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isViewVisible = true;
            lazyLoad();
        } else {
            isViewVisible = false;

        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.daikaotest_item, container, false);
        if (getArguments() != null) {
            rowsBean = (DaikaoAndHavetestCourseBean.RowsBean) getArguments().getSerializable(ARG_PARAM1);
            position = getArguments().getInt(ARG_PARAM2);

        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreate = true;
        lazyLoad();
    }

    private void lazyLoad() {
        if (isViewCreate && isViewVisible) {
            initView();
        }
    }

    private void initView() {
    //    animation = AnimationUtils.loadAnimation(getContext(), R.anim.change_color);
        int sn = rowsBean.getSn();

        if(rowsBean.getUserOption()==null) {
            SharedPreferences sp = getActivity().getSharedPreferences("AccidentTrainingExaminationActivity",
                    Context.MODE_PRIVATE);
            String checkboxopition = sp.getString("checkboxopition"+ sn, "");
            String radioopition = sp.getString("radioopition"+ sn, "");
            EventBus.getDefault().post(new MessageEventTest(checkboxopition, sn, radioopition));
        }else {
            if(rowsBean.getQtype()==3||rowsBean.getQtype()==1) {
                EventBus.getDefault().post(new MessageEventTest("", sn, rowsBean.getUserOption()));
            }else if(rowsBean.getQtype()==2)
            {
                SharedPreferences sp = getActivity().getSharedPreferences("AccidentTrainingExaminationActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("checkboxopition"+ sn,rowsBean.getUserOption());
                edit.commit();
                EventBus.getDefault().post(new MessageEventTest(rowsBean.getUserOption(), sn, ""));
            }
        }
        TextView tv_desc = (TextView) view.findViewById(R.id.tv_daikao_test);
        TextView tv_scon = (TextView) view.findViewById(R.id.tv_daikao_test2);
        tv_scon.setText("分数：" + rowsBean.getScore() + "分");
        ImageView img_daikao = (ImageView) view.findViewById(R.id.img_daikao_test_item);
        if (rowsBean.getUrl() == null) {
            img_daikao.setVisibility(View.GONE);

        } else {
            img_daikao.setVisibility(View.VISIBLE);
            if(rowsBean.getUrl().contains("aliyuncs.com"))
            {
                Picasso.with(getContext()).load(Uri.parse(rowsBean.getUrl())).placeholder(R.mipmap.no_data2).into(img_daikao);
            }else{

                Picasso.with(getContext()).load(Uri.parse(AppInterfaceConfig.getRequestUrl(rowsBean.getUrl()))).placeholder(R.mipmap.no_data2).into(img_daikao);
            }
        }
        String optionA = rowsBean.getOptionA();
        String optionB = rowsBean.getOptionB();
        String optionC = rowsBean.getOptionC();
        String optionD = rowsBean.getOptionD();
        String optionE = rowsBean.getOptionE();
        String optionF = rowsBean.getOptionF();
        opitionList.clear();
        opitionList.add(optionA);
        opitionList.add(optionB);
        opitionList.add(optionC);
        opitionList.add(optionD);
        opitionList.add(optionE);
        opitionList.add(optionF);
        ArrayList<String> opitionnewList=new ArrayList<>();
        opitionnewList.clear();
        for (int i = 0; i < opitionList.size(); i++) {
            if(opitionList.get(i)!=null&&!opitionList.get(i).equals(""))
            {
                opitionnewList.add(opitionList.get(i));
            }
        }
        int question_select1 = rowsBean.getQuestion_select1();
        int question_select2 = rowsBean.getQuestion_select2();
        int question_select3 = rowsBean.getQuestion_select3();
        int question_select4= rowsBean.getQuestion_select4();
        int question_select5 = rowsBean.getQuestion_select5();
        int question_select6 = rowsBean.getQuestion_select6();

        checkboxList.clear();
        checkboxList.add(question_select1);
        checkboxList.add(question_select2);
        checkboxList.add(question_select3);
        checkboxList.add(question_select4);
        checkboxList.add(question_select5);
        checkboxList.add(question_select6);
        ArrayList<Integer> checkboxListnew=new ArrayList<>();
        checkboxListnew.clear();
        for (int i = 0; i < opitionnewList.size(); i++) {
            checkboxListnew.add(checkboxList.get(i));
        }

        String tag=DaikaoAndHavetestCourseBean.getQuestionTypeStr(rowsBean.getQtype());
        CharSequence content=tag+"  "+(rowsBean.getSeqNo()) + ". " + rowsBean.getQuestionDesc();
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        builder.setSpan(new ImageSpan(getActivity(),R.drawable.text_background){
            @Override
            public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
                paint.setColor(Color.parseColor("#1F80C4"));
                paint.setTextSize(DensityUtils.sp2px(getContext(), 11));
                canvas.drawText(text.subSequence(start, end).toString(), x+ DensityUtils.dp2px(getContext(), 5), y- DensityUtils.dp2px(getContext(), 3), paint);
                super.draw(canvas, text, start, end, x, top, y, bottom- DensityUtils.dp2px(getContext(), 1), paint);
            }
        }, 0, tag.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_desc.setText(builder);

        if (rowsBean.getQtype() == DaikaoAndHavetestCourseBean.TYPE_Multiple_Choice) {//多项选择题
            updateCheckBoxView(opitionnewList, sn,checkboxListnew);
        } else  if(rowsBean.getQtype() == DaikaoAndHavetestCourseBean.TYPE_True_OR_False){//判断题
            updateRadioView(opitionnewList, sn);
        }else  if(rowsBean.getQtype() == DaikaoAndHavetestCourseBean.TYPE_Single_Choice){//单选题
            updateRadioView(opitionnewList, sn);
        }
    }
    //字母排序
    public String sortString(String str) {

        //  System.out.println("排序前的字符串是:" + str);
        LogUtils.e("排序前的字符串是:", str);
        // 排序前字符串转换为字符数组
        char[] cs = str.toCharArray();

        // 升序排序
        for (int i = 0; i < cs.length - 1; i++) {
            for (int j = 0; j < cs.length - 1 - i; j++) {

                char temp = 0;
                if (cs[j] > cs[j + 1]) {

                    temp = cs[j];
                    cs[j] = cs[j + 1];
                    cs[j + 1] = temp;
                }
            }
        }

        // 排序以后的字符串
        String newString = "";

        for (int i = 0; i < cs.length; i++) {
            newString += cs[i];
        }
        // 打印排序以后的字符串
        LogUtils.e("排序后的字符串是:", newString);
        return newString;

    }

    /**
     * 添加多选按钮
     * @param
     * @param opitionnewList
     * @param sn
     * @param checkboxListnew
     */
    private void updateCheckBoxView(ArrayList<String> opitionnewList, final int sn, ArrayList<Integer> checkboxListnew) {
        final    LinearLayout layout = (LinearLayout) view.findViewById(R.id.check_options);
        layout.removeAllViews();
        for (int i = 0; i < opitionnewList.size(); i++) {
            String opition = opitionnewList.get(i);
        final     CheckBox checkboxView = (CheckBox) LayoutInflater.from(getActivity()).inflate(R.layout.item_checkbox_new, null);
            checkboxView.setText(QuestionAnswerUtils.getAnswerStr(i)+opition);
            checkboxView.setTag(i);
                if (checkboxListnew.get(i) == i) {
                    checkboxView.setChecked(true);

                } else {
                    checkboxView.setChecked(false);
                }

            checkboxView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        SharedPreferences sp = getActivity().getSharedPreferences("AccidentTrainingExaminationActivity",
                                Context.MODE_PRIVATE);
                        String s2 = sp.getString("checkboxopition"+sn, "");
                        int op= (int) buttonView.getTag();
                        StringBuffer s1 = new StringBuffer(s2);
                        if(op==0)
                        {
                            s1.append("A");
                            rowsBean.setQuestion_select1(0);
                        }else if(op==1)
                        {
                            s1.append("B");
                            rowsBean.setQuestion_select2(1);
                        }else if(op==2)
                        {
                            s1.append("C");
                            rowsBean.setQuestion_select3(2);
                        }else if(op==3)
                        {
                            s1.append("D");
                            rowsBean.setQuestion_select4(3);
                        }else if(op==4)
                        {
                            s1.append("E");
                            rowsBean.setQuestion_select5(4);
                        }else if(op==5)
                        {
                            s1.append("F");
                            rowsBean.setQuestion_select6(5);
                        }
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("checkboxopition"+sn,s1.toString());
                        edit.putInt("sn",sn);
                        edit.commit();
                        EventBus.getDefault().post(new MessageEventTest(s1.toString(),sn,""));
                    }else{
                        SharedPreferences sp = getActivity().getSharedPreferences("AccidentTrainingExaminationActivity",
                                Context.MODE_PRIVATE);
                        String checkboxopition = sp.getString("checkboxopition"+sn, "");
                        int op= (int) buttonView.getTag();
                        String checkboxopitionnew="";
                        if(op==0)
                        {
                            checkboxopitionnew = checkboxopition.replace("A", "");
                            rowsBean.setQuestion_select1(-1);

                        }else if(op==1)
                        {
                            checkboxopitionnew = checkboxopition.replace("B", "");
                            rowsBean.setQuestion_select2(-1);

                        }else if(op==2)
                        {
                            checkboxopitionnew = checkboxopition.replace("C", "");
                            rowsBean.setQuestion_select3(-1);

                        }else if(op==3)
                        {
                            checkboxopitionnew = checkboxopition.replace("D", "");
                            rowsBean.setQuestion_select4(-1);

                        }else if(op==4)
                        {
                            checkboxopitionnew = checkboxopition.replace("E", "");
                            rowsBean.setQuestion_select5(-1);

                        }else if(op==5)
                        {
                            checkboxopitionnew = checkboxopition.replace("F", "");
                            rowsBean.setQuestion_select6(-1);

                        }
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("checkboxopition"+sn,checkboxopitionnew);
                        edit.putInt("sn",sn);
                        edit.commit();
                        EventBus.getDefault().post(new MessageEventTest(checkboxopitionnew,sn,""));
                    }


                }
            });

            layout.addView(checkboxView);
        }

    }
    /**
     * 添加单选按钮
     * @param opitionnewList
     * @param
     */
    private void updateRadioView(final ArrayList<String> opitionnewList, final int sn) {
        final RadioGroup layout = (RadioGroup) view.findViewById(R.id.rg_options);
        layout.removeAllViews();
        int checkId = -1;
        for (int i = 0; i < opitionnewList.size();i++) {
            final String opition = opitionnewList.get(i);
            final RadioButton radioView = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.item_radio_new, null, true);
            final RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            radioView.setLayoutParams(layoutParams);
            radioView.setText(QuestionAnswerUtils.getAnswerStr(i)+opition);
            radioView.setTag(i);
            radioView.setId(i);
                if (rowsBean.getQuestion_select() == i) {
                    checkId=i;
                }

            radioView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                     if(isChecked){
                        int op= (int) buttonView.getTag();
                         String radioopition="";
                         SharedPreferences sp = getActivity().getSharedPreferences("AccidentTrainingExaminationActivity",
                                 Context.MODE_PRIVATE);
                      //   int apromptMark = sp.getInt("apromptMark", 0);

                        if(op==0)
                        {
                            radioopition="A";
                            rowsBean.setQuestion_select(0);
                        }else if(op==1)
                        {
                            radioopition="B";
                            rowsBean.setQuestion_select(1);

                        }
                        else if(op==2)
                        {
                            radioopition="C";
                            rowsBean.setQuestion_select(2);
                        }
                        else if(op==3)
                        {
                            radioopition="D";
                            rowsBean.setQuestion_select(3);
                        }else if(op==4)
                        {
                            radioopition="E";
                            rowsBean.setQuestion_select(4);
                        }  else if(op==5)
                        {
                            radioopition="F";
                            rowsBean.setQuestion_select(5);
                        }
                         radioView.setChecked(true);

                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("radioopition"+sn,radioopition);
                        edit.putInt("sn",sn);
                        edit.commit();
                        EventBus.getDefault().post(new MessageEventTest("",sn,radioopition));

                    }
                }
            });
            layout.addView(radioView);
        }
        if(checkId!=-1){
            layout.clearCheck();
            layout.check(checkId);

        }
    }


}
